﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace VsSourceCpoy.Helper
{
    public enum VSVersion
    {
        VS2005,
        VS2008,
        VS2010,
        Unkonw
    }

    public class VsVersionCheck
    {
        public static VSVersion GetVsVersionFromSlnFile(string slnFile)
        {
            string formatVersion = GetSlnFormatVersoin(slnFile);
            string versionStr2008 = "10.00";
            string versionStr2010 = "11.00";
            if (versionStr2008.Equals(formatVersion))
            {
                return VSVersion.VS2008;
            }
            else if (versionStr2010.Equals(formatVersion))
            {
                return VSVersion.VS2010;
            }
            return VSVersion.Unkonw;
        }

        public static VSVersion GetVsVersionFromCsprojFile(string slnFile)
        {
            string formatVersion = CheckCsprojVersoin(slnFile);
            string toolVersion2008 = "3.5";
            string toolVersion2010 = "4.0";
            if (toolVersion2008.Equals(formatVersion))
            {
                return VSVersion.VS2008;
            }
            else if (toolVersion2010.Equals(formatVersion))
            {
                return VSVersion.VS2010;
            }
            return VSVersion.Unkonw;
        }

        private static string CheckCsprojVersoin(string slnFile)
        {
            string attr = null;
            try
            {
                XElement pgElement = XElement.Load(slnFile);
                attr = pgElement.Attribute("ToolsVersion").Value;
                return attr;
            }
            catch
            {
                throw new VersionUnsupportException("文件解析错误：" + slnFile);
            }
        }

        private static string GetSlnFormatVersoin(string slnFile)
        {
            string firstLine = TxtFileHelper.ReadUntil(slnFile, new GetLineFilter()
            {
                DeleteEmptyLine = true,
                TrimLine = true
            }, (line, idx) => idx == 1).FirstOrDefault();
            if (!string.IsNullOrEmpty(firstLine))
            {
                string formatVersion = "Format Version";
                int idx = firstLine.IndexOf(formatVersion, StringComparison.OrdinalIgnoreCase);
                if (idx > 0)
                {
                    string v = firstLine.Substring(idx + formatVersion.Count()).Trim();
                    return v;
                }
            }
            return null;
        }
    }
}
